﻿using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;
using System;
using System.Linq;
using System.ServiceProcess;
using System.Threading;
using TcpServer.DataProcessor;

namespace Biz
{
    public partial class BizProcessor : ServiceBase
    {
        private ILog log = LogManager.GetLogger(typeof(BizProcessor));
        int milliSeconds = 10;

        public BizProcessor()
        {
            InitializeComponent();
        }
        //test
        public void Main()
        {
            OnStart(null);
        }
        protected override void OnStart(string[] args)
        {
            //启动各路线程
            new Thread(Biz).Start();
            new Thread(IssueLimitValue).Start();
            log.Info("各路线程启动完成...");
        }
        protected override void OnStop()
        {
            log.Info("The processor Stoped!");
            Environment.Exit(0);
        }
        public void Biz(object state)
        {
            while (true)
            {
                try
                {
                    using (var ctx = new GatewayMonitorContext())
                    using (DustContext context = new DustContext())
                    {

                        var items = ctx.received_msg.Where(t => t.processed_flag.Equals("NotProcessed"))
                            .OrderBy(t => t.datatime)
                            .Take(1000).ToList();
                        log.Debug("Be processed:" + items.Count);
                        foreach (var item in items)
                        {
                            var cn = Parser.GetStringByKey("CN", item.received_string);
                            log.Debug(
                                Thread.CurrentThread.GetHashCode() + "-Biz" + "开始处理" + cn + ":" + item.received_string);
                            switch (cn)
                            {
                                case "2011":
                                    Platform2011Processor.Persist(context, item.received_string);
                                    Alarm2011Processor.Persist(context, item.received_string);
                                    break;
                                case "2021":
                                    Platform2021Processor.Persist(context, item.received_string);
                                    AlarmAvgProcessor.Persist(context, item.received_string);
                                    break;
                                case "2031":
                                    Platform2031Processor.Persist(context, item.received_string);
                                    Platform2031ToMonthProcessor.Persist(context, item.received_string);
                                    Platform2031ToYearProcessor.Persist(context, item.received_string);
                                    AlarmAvgProcessor.Persist(context, item.received_string);
                                    LatitudeLongitude2031Processor.Persist(context, item.received_string);
                                    break;
                                case "2051":
                                    Platform2051Processor.Persist(context, item.received_string);
                                    AlarmAvgProcessor.Persist(context, item.received_string);
                                    break;
                                case "2061":
                                    Platform2061Processor.Persist(context, item.received_string);
                                    AlarmAvgProcessor.Persist(context, item.received_string);
                                    break;
                                case "9011":
                                    Platform9011Processor.Persist(context, item.received_string);
                                    break;
                                case "9012":
                                    Platform9012Processor.Persist(context, item.received_string);
                                    break;
                                case "3081":
                                    Platform3081Processor.Persist(context, item.received_string);
                                    break;
                            }

                            item.processed_flag = ProcessFlag.ProcessingFinished.ToString();
                            ThreadUtil.Sleep(milliSeconds);
                        }

                        ctx.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                ThreadUtil.Sleep(1000);
            }
            // ReSharper disable once FunctionNeverReturns
        }

        public void IssueLimitValue(object state)
        {
            while (true)
            {
                try
                {
                    using (var ctx = new DustContext())
                    using (var gCtx = new GatewayMonitorContext())
                    {
                        var issueItems = ctx.V_Threshold.Where(t => t.DevCode != null).Where(t => !t.执行结果.Contains("不同步")).Where(t => !t.执行结果.Contains("成功")).ToList();
                        foreach (var issue in issueItems)
                        {
                            var setion = BaseInfoBufferAndHelper.GetAlarmThrsholdTimeType(issue.时间类型名称);
                            var qn = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            var result = "QN=" + qn
                                         + ";ST=20;CN=3088;PW=123456" + ";MN=" + issue.DevCode
                                         + ";Flag=1;CP=&&" + issue.因子代码 + "-Thd=" + issue.报警阈值.ToString("f2")
                                + "," + issue.因子代码 + "-DateType=" + issue.报警限值时间类型ID + ","
                                + issue.因子代码 + "-BeginTime=" + setion.BeginHour.ToString("D2") + setion.BeginMinute.ToString("D2") + ","
                                + issue.因子代码 + "-EndTime=" + setion.EndHour.ToString("D2") + setion.EndMinute.ToString("D2") + ","
                                + issue.因子代码 + "-SiteType=" + issue.SiteTypeID + "&&";
                            result = "##" + result.Length.ToString("D4") + result + Crc.WrapByCrc(result, "monitor") + "\r\n";

                            var now = DateTime.Now;
                            send_ctr_cmd cmd = new send_ctr_cmd
                            {
                                cn = "3088",
                                mn = issue.DevCode,
                                qn = qn,
                                is_sent = false,
                                send_string = result,
                                sent_time = now,
                                send_time = now
                            };
                            gCtx.send_ctr_cmd.Add(cmd);
                            gCtx.SaveChanges();
                            var thd = ctx.SetFactorThresholds.FirstOrDefault(t => t.ID == issue.ID);
                            if (thd != null)
                            {
                                thd.QN = qn;
                                ctx.SaveChanges();
                            }
                            log.Info("IssueThreshold" + result);
                            ThreadUtil.Sleep(milliSeconds);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                finally
                {
                    ThreadUtil.Sleep(10000);
                }
            }
        }
    }
}
